'use strict';

const BaseService = require('./base');
const wxconfig = require("../../config/wx");
const WXBizDataCrypt = require('../../config/WXBizDataCrypt');
class ParentService extends BaseService {
  constructor(ctx) {
    super(ctx, 'Parent');
  }

  // 自定义排序规则
  pageOrder() {
    return [['create_time', 'DESC']];
  }

  listOrder() {
    return [['create_time', 'DESC']];
  }

  // 微信登录
  async loginForm(wx_openid, phone) {
    // 查找或创建用户
    let parent = await this.ctx.model.Parent.findOne({
      where: { wx_openid }
    });

    if (!parent) {
      // 新用户，创建记录
      parent = await this.create({
        wx_openid,
        phone,
        name: phone,
        status: 1
      });
    }

    return parent;
  }


  async exchangeCodeForSessionKey(code) {
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxconfig.appid}&secret=${wxconfig.secret}&js_code=${code}&grant_type=authorization_code`;
    const response = await this.ctx.curl(url, { dataType: 'json' });
    const data = response.data;
    console.log(data)
    if (!data.session_key || !data.openid) {
      throw new Error('Failed to exchange code for session_key and openid');
    }

    return {
      session_key: data.session_key,
      openid: data.openid,
    };
  }
  async decryptPhoneNumber(session_key, encryptedData, iv) {
    const pc = new WXBizDataCrypt(wxconfig.appid, session_key);
    const data = {};

    const errCode = pc.decryptData(encryptedData, iv, data);
    return errCode.phoneNumber
  }

  async wxLogin(data) {
    const { code, encryptedData, iv } = data;
    try {
      const { session_key, openid} = await this.exchangeCodeForSessionKey(code)
      const phoneNumber = await this.decryptPhoneNumber(session_key, encryptedData, iv)
      return await this.loginForm(openid, phoneNumber)
    } catch (error) {
      console.log('error',error)
      throw new Error('登录失败');
    }
  }


  // 获取孩子列表
  getChildren(parent_id) {
    return this.ctx.model.Student.findAll({
      where: {parent_id},
      order: [['grade', 'DESC']]
    });
  }

  // 查看孩子的课程记录
  async getChildCourses(student_id) {
    const courses = await this.ctx.model.CourseRecord.findAll({
      where: { student_id },
      order: [['create_time', 'DESC']],
      include: [{
        model: this.ctx.model.Course,
        attributes: ['id', 'name', 'teacher', 'schedule', 'create_time', 'updated_time'],
      }],
      attributes: [
        'id', 'student_id', 'course_id', 'status', 'create_time', 'updated_time'
      ]
    });
    return courses;
  }
}

module.exports = ParentService;
